#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:ouyang time:2023/4/5

import json
import threading
import time
import socket
import base64
import os
import copy
import signal
from collections import deque


class TCPClient(threading.Thread):
    """
    收集车辆的信息
    """
    def __init__(self, serve_ip):

        threading.Thread.__init__(self)

        """ 定义常量 """
        self.run_environment = 'pc'

        """初始化UDP服务端"""
        self.server_ip = serve_ip
        self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server_port = 61121
        self.connect_obj_buff = deque()  # UDP接收数据缓存区
        self.tcp_client.connect((self.server_ip, self.server_port))  # 连接目标服务器

        """socket连接状态、数据缓存"""
        self.connect_sta = 0      # 连接状态变为断开状态
        self.thread_run = 0       # 线程结束状态
        self.pre_data = ''
        self.temp_buff = deque()  # 接收数据缓冲区--原始数据
        self.temp_data_list = deque()  # 接收数据缓冲区--解析数据
        self.task_all_server_que = deque()

    def run(self):
            self.udp_server_task()

    def udp_server_task(self):
        while True:
            try:
                self.temp_buff.append(self.rev_message())  # 接收数据
                self.get_data()
            except Exception as e:
                print(e)
                return 0

    def rev_message(self):
        data = self.tcp_client.recv(65535)
        print("rev:", data)
        if not data:
            raise Exception
        else:
            buffer = data.decode()
            return buffer

    def send_json_message(self, dic_msg):

        self.tcp_client.send(dic_msg)

    def send_simple_message(self, message):
        print('send_message')
        self.tcp_client.send(message.encode('utf-8'))

    def split_receive_data(self, receive_data):
        """
        用于分开接收到的粘连、断开的数据
        先找到开头的数据，再找到尾部数据，进行分割
        :param receive_data: 传入接收的数据
        :return:
        """
        start_sta = receive_data.split('$')
        num = len(start_sta)
        for i in range(num):
            if start_sta[i] != '':
                stop_sta = start_sta[i].split('#')
                if len(stop_sta) == 2:
                    if self.pre_data == '':
                        self.temp_data_list.append(stop_sta[0])
                    else:
                        self.pre_data += stop_sta[0]
                        self.temp_data_list.append(self.pre_data)
                        self.pre_data = ''
                else:
                    self.pre_data += stop_sta[0]

    def get_data(self):

        if len(self.temp_buff) != 0:
            data_buff = self.temp_buff.popleft()
            self.split_receive_data(data_buff)  # 用头标志把结点信息隔开

        if len(self.temp_data_list) != 0:
            temp_buff = self.temp_data_list.popleft()
            print(temp_buff)
            #             # print(json_buff)
            self.task_all_server_que.append(temp_buff)

    def get_offload_data(self):
        """
        外部调用接口，返回收集的任务
        :return:
        """
        temp_task = []
        count = len(self.task_all_server_que)
        if count != 0:
            for i in range(0, count):
                temp_task.append(self.task_all_server_que.popleft())
            print(temp_task)
            return temp_task
        else:
            return None


if __name__ == '__main__':
    c = TCPClient('127.0.0.1')
    c.run()

